package com.config;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;

@Intercepts( //配置拦截
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
)
@Component //等待解决办法
public class MybatisFillField implements Interceptor {
    //获取到拦截的对象，底层也是通过代理来实现的，实际上是拿到一个目标的代理对象
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    //获取配置文件中设置的阈值等参数
    @Override
    public void setProperties(Properties properties) {

    }
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
        //获取操作类型，crud
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        //获取参数
        Object parameter = invocation.getArgs()[1];
        System.out.println(Arrays.toString(invocation.getArgs()));
        Field[]fields = parameter.getClass().getDeclaredFields();


        for(Field field: fields){
            //注入对应的属性值
            if (field.getName().equals("createBy")&&SqlCommandType.INSERT.equals(sqlCommandType)){
                field.setAccessible(true);
                field.set(parameter,new Date());
            }
            if (field.getName().equals("updateTime")&&SqlCommandType.UPDATE.equals(sqlCommandType)){
                field.setAccessible(true);
                field.set(parameter,new Date());
            }
        }
        Object object = invocation.proceed();

        return object;
    }

}
